"""
多轮对话系统
集成 RAG 检索增强生成功能
支持对话历史管理、对话列表、新建对话等功能
"""

import os
import sys
import json
import uuid
from typing import List, Dict, Any, Optional
from datetime import datetime
from pathlib import Path

# 添加项目根目录到路径
project_root = Path(__file__).parent.parent
sys.path.insert(0, str(project_root))

# DashScope 相关（通义千问）
try:
    import dashscope
    from dashscope import Generation
    DASHSCOPE_AVAILABLE = True
except ImportError:
    print("警告: DashScope 未找到，请安装: pip install dashscope")
    DASHSCOPE_AVAILABLE = False
    dashscope = None
    Generation = None

# 导入 RAG 系统
try:
    from xiaohongshu_rag.rag_PDF import RAGSystem
    RAG_AVAILABLE = True
except ImportError:
    print("警告: RAG 系统未找到，将仅使用基础对话功能")
    RAG_AVAILABLE = False
    RAGSystem = None

# 导入 Redis 工具
try:
    from utils.myredis import Mredis
    REDIS_AVAILABLE = True
except ImportError:
    print("警告: Redis 工具未找到，对话信息将仅存储在内存中")
    REDIS_AVAILABLE = False
    Mredis = None


class ChatSystem:
    """多轮对话系统类"""
    
    def __init__(self, api_key: str = "sk-2c036d80d14a443f8769e072bb09a2e1", enable_rag: bool = True):
        """
        初始化对话系统
        
        Args:
            api_key: DashScope API Key（通义千问密钥）
            enable_rag: 是否启用 RAG 检索增强生成
        """
        if not DASHSCOPE_AVAILABLE:
            raise ImportError("DashScope 未安装，请安装: pip install dashscope")
        
        # 设置 DashScope API Key
        dashscope.api_key = api_key
        self.api_key = api_key
        self.llm_model = "qwen3-max"  # 使用 qwen3-max 模型
        
        # 对话管理（内存存储，用于快速访问）
        self.conversations: Dict[str, List[Dict[str, Any]]] = {}  # 存储所有对话历史
        self.current_conversation_id: Optional[str] = None  # 当前对话ID
        
        # Redis 连接（用于持久化存储）
        self.redis_client = None
        if REDIS_AVAILABLE:
            try:
                self.redis_client = Mredis(db=1)  # 使用db=1存储对话数据
                print("[初始化] Redis 连接成功，对话信息将持久化存储")
            except Exception as e:
                print(f"[初始化] Redis 连接失败: {e}，对话信息将仅存储在内存中")
                self.redis_client = None
        
        # RAG 系统
        self.enable_rag = enable_rag and RAG_AVAILABLE
        self.rag_system = None
        
        if self.enable_rag:
            try:
                print("[初始化] 正在初始化 RAG 系统...")
                self.rag_system = RAGSystem(api_key=api_key)
                print("[初始化] RAG 系统初始化成功")
            except Exception as e:
                print(f"[初始化] RAG 系统初始化失败: {e}")
                print("[初始化] 将仅使用基础对话功能")
                self.enable_rag = False
                self.rag_system = None
        
        # 对话元数据（存储对话标题、创建时间等，内存缓存）
        self.conversation_metadata: Dict[str, Dict[str, Any]] = {}
        
        # Redis Key 前缀
        self.redis_prefix = "chat"
        
        print(f"[初始化] 对话系统初始化完成，RAG 功能: {'已启用' if self.enable_rag else '未启用'}，Redis 存储: {'已启用' if self.redis_client else '未启用'}")
    
    def create_conversation(self, title: Optional[str] = None) -> str:
        """
        创建新对话
        
        Args:
            title: 对话标题（可选，如果不提供则使用第一条消息作为标题）
        
        Returns:
            新对话的 ID
        """
        conversation_id = str(uuid.uuid4())
        self.conversations[conversation_id] = []
        
        metadata = {
            "title": title or "新对话",
            "created_at": datetime.now().isoformat(),
            "updated_at": datetime.now().isoformat(),
            "message_count": 0
        }
        self.conversation_metadata[conversation_id] = metadata
        self.current_conversation_id = conversation_id
        
        # 存储到 Redis
        if self.redis_client:
            try:
                self._save_conversation_to_redis(conversation_id, metadata, [])
            except Exception as e:
                print(f"[Redis] 保存对话到Redis失败: {e}")
        
        print(f"[对话] 创建新对话: {conversation_id}")
        return conversation_id
    
    def _save_conversation_to_redis(self, conversation_id: str, metadata: Dict[str, Any], messages: List[Dict[str, Any]]):
        """
        保存对话信息到Redis
        
        Args:
            conversation_id: 对话ID
            metadata: 对话元数据
            messages: 对话消息列表
        """
        if not self.redis_client:
            return
        
        try:
            # 使用Hash存储对话元数据
            metadata_key = f"{self.redis_prefix}:metadata:{conversation_id}"
            self.redis_client.hash_add(metadata_key, "title", metadata.get("title", "新对话").encode('utf-8'))
            self.redis_client.hash_add(metadata_key, "created_at", metadata.get("created_at", "").encode('utf-8'))
            self.redis_client.hash_add(metadata_key, "updated_at", metadata.get("updated_at", "").encode('utf-8'))
            self.redis_client.hash_add(metadata_key, "message_count", str(metadata.get("message_count", 0)).encode('utf-8'))
            
            # 使用List存储对话消息（JSON格式）
            messages_key = f"{self.redis_prefix}:messages:{conversation_id}"
            # 清空旧消息
            self.redis_client.r.delete(messages_key)
            # 添加新消息
            for msg in messages:
                msg_json = json.dumps(msg, ensure_ascii=False)
                self.redis_client.list_rpush(messages_key, msg_json.encode('utf-8'))
            
            # 使用Sorted Set存储对话列表（按更新时间排序，score为时间戳）
            list_key = f"{self.redis_prefix}:list"
            updated_at = metadata.get("updated_at", "")
            if updated_at:
                # 将时间字符串转换为时间戳作为score
                try:
                    dt = datetime.fromisoformat(updated_at.replace('Z', '+00:00'))
                    timestamp = dt.timestamp()
                except:
                    timestamp = datetime.now().timestamp()
                # 添加到有序集合（使用zadd，兼容不同redis版本）
                try:
                    # 新版本语法（redis-py 3.0+）
                    self.redis_client.r.zadd(list_key, {conversation_id: timestamp})
                except TypeError:
                    # 旧版本语法（redis-py 2.x）
                    self.redis_client.r.zadd(list_key, timestamp, conversation_id)
                
        except Exception as e:
            print(f"[Redis] 保存对话到Redis失败: {e}")
            import traceback
            traceback.print_exc()
    
    def _load_conversation_from_redis(self, conversation_id: str) -> Optional[Dict[str, Any]]:
        """
        从Redis加载对话信息
        
        Args:
            conversation_id: 对话ID
        
        Returns:
            包含metadata和messages的字典，如果不存在返回None
        """
        if not self.redis_client:
            return None
        
        try:
            # 加载元数据
            metadata_key = f"{self.redis_prefix}:metadata:{conversation_id}"
            metadata_raw = self.redis_client.hash_getall(metadata_key)
            if not metadata_raw:
                return None
            
            # 解码元数据
            metadata = {}
            for key, value in metadata_raw.items():
                key_str = key.decode('utf-8') if isinstance(key, bytes) else key
                value_str = value.decode('utf-8') if isinstance(value, bytes) else value
                if key_str == "message_count":
                    metadata[key_str] = int(value_str)
                else:
                    metadata[key_str] = value_str
            
            # 加载消息
            messages_key = f"{self.redis_prefix}:messages:{conversation_id}"
            messages_raw = self.redis_client.r.lrange(messages_key, 0, -1)
            messages = []
            for msg_bytes in messages_raw:
                msg_str = msg_bytes.decode('utf-8') if isinstance(msg_bytes, bytes) else msg_bytes
                messages.append(json.loads(msg_str))
            
            return {
                "metadata": metadata,
                "messages": messages
            }
        except Exception as e:
            print(f"[Redis] 从Redis加载对话失败: {e}")
            return None
    
    def get_conversation_list(self) -> List[Dict[str, Any]]:
        """
        获取对话列表（从Redis获取，只返回最新5条）
        
        Returns:
            对话列表，包含对话ID、标题、创建时间、更新时间、消息数量（最多5条）
        """
        conversation_list = []
        
        if self.redis_client:
            try:
                # 从Redis的Sorted Set获取最新的对话ID（按更新时间倒序）
                list_key = f"{self.redis_prefix}:list"
                # 获取最新的5个对话ID（按score降序）
                conversation_ids = self.redis_client.r.zrevrange(list_key, 0, 4)  # 只取前5个
                
                for conv_id_bytes in conversation_ids:
                    conv_id = conv_id_bytes.decode('utf-8') if isinstance(conv_id_bytes, bytes) else conv_id_bytes
                    
                    # 从Redis加载对话信息
                    conv_data = self._load_conversation_from_redis(conv_id)
                    if conv_data:
                        metadata = conv_data["metadata"]
                        messages = conv_data["messages"]
                        
                        # 获取最后一条消息作为预览
                        last_message = None
                        if messages:
                            last_message_obj = messages[-1]
                            if last_message_obj.get("role") == "user":
                                last_message = last_message_obj.get("content", "")[:50]
                            elif last_message_obj.get("role") == "assistant":
                                last_message = last_message_obj.get("content", "")[:50]
                        
                        conversation_list.append({
                            "conversation_id": conv_id,
                            "title": metadata.get("title", "未命名对话"),
                            "created_at": metadata.get("created_at", ""),
                            "updated_at": metadata.get("updated_at", ""),
                            "message_count": metadata.get("message_count", 0),
                            "last_message": last_message,
                            "is_current": conv_id == self.current_conversation_id
                        })
                        
                        # 同步到内存（用于快速访问）
                        self.conversation_metadata[conv_id] = metadata
                        self.conversations[conv_id] = messages
            except Exception as e:
                print(f"[Redis] 从Redis获取对话列表失败: {e}")
                # 降级到内存存储
                pass
        
        # 如果Redis获取失败或未启用，从内存获取
        if not conversation_list:
            for conv_id, metadata in self.conversation_metadata.items():
                # 获取最后一条消息作为预览
                messages = self.conversations.get(conv_id, [])
                last_message = None
                if messages:
                    last_message_obj = messages[-1]
                    if last_message_obj.get("role") == "user":
                        last_message = last_message_obj.get("content", "")[:50]
                    elif last_message_obj.get("role") == "assistant":
                        last_message = last_message_obj.get("content", "")[:50]
                
                conversation_list.append({
                    "conversation_id": conv_id,
                    "title": metadata.get("title", "未命名对话"),
                    "created_at": metadata.get("created_at", ""),
                    "updated_at": metadata.get("updated_at", ""),
                    "message_count": metadata.get("message_count", 0),
                    "last_message": last_message,
                    "is_current": conv_id == self.current_conversation_id
                })
        
        # 按更新时间倒序排列
        conversation_list.sort(key=lambda x: x.get("updated_at", ""), reverse=True)
        
        # 只返回最新5条
        return conversation_list[:5]
    
    def switch_conversation(self, conversation_id: str) -> bool:
        """
        切换对话
        
        Args:
            conversation_id: 对话ID
        
        Returns:
            是否切换成功
        """
        # 先尝试从内存加载
        if conversation_id in self.conversations:
            self.current_conversation_id = conversation_id
            print(f"[对话] 切换到对话: {conversation_id}")
            return True
        
        # 如果内存中没有，尝试从Redis加载
        if self.redis_client:
            conv_data = self._load_conversation_from_redis(conversation_id)
            if conv_data:
                # 同步到内存
                self.conversation_metadata[conversation_id] = conv_data["metadata"]
                self.conversations[conversation_id] = conv_data["messages"]
                self.current_conversation_id = conversation_id
                print(f"[对话] 从Redis加载并切换到对话: {conversation_id}")
                return True
        
        print(f"[对话] 对话不存在: {conversation_id}")
        return False
    
    def delete_conversation(self, conversation_id: str) -> bool:
        """
        删除对话
        
        Args:
            conversation_id: 对话ID
        
        Returns:
            是否删除成功
        """
        deleted = False
        
        # 从内存删除
        if conversation_id in self.conversations:
            del self.conversations[conversation_id]
            deleted = True
        
        if conversation_id in self.conversation_metadata:
            del self.conversation_metadata[conversation_id]
            deleted = True
        
        # 从Redis删除
        if self.redis_client:
            try:
                # 删除元数据
                metadata_key = f"{self.redis_prefix}:metadata:{conversation_id}"
                self.redis_client.r.delete(metadata_key)
                
                # 删除消息
                messages_key = f"{self.redis_prefix}:messages:{conversation_id}"
                self.redis_client.r.delete(messages_key)
                
                # 从对话列表中删除
                list_key = f"{self.redis_prefix}:list"
                self.redis_client.r.zrem(list_key, conversation_id)
                
                deleted = True
            except Exception as e:
                print(f"[Redis] 从Redis删除对话失败: {e}")
        
        # 如果删除的是当前对话，清空当前对话ID
        if self.current_conversation_id == conversation_id:
            self.current_conversation_id = None
        
        if deleted:
            print(f"[对话] 删除对话: {conversation_id}")
            return True
        else:
            print(f"[对话] 对话不存在: {conversation_id}")
            return False
    
    def get_conversation_history(self, conversation_id: Optional[str] = None) -> List[Dict[str, Any]]:
        """
        获取对话历史
        
        Args:
            conversation_id: 对话ID（如果为None，则返回当前对话的历史）
        
        Returns:
            对话历史列表
        """
        target_id = conversation_id or self.current_conversation_id
        if not target_id:
            return []
        
        # 先尝试从内存获取
        if target_id in self.conversations:
            return self.conversations[target_id]
        
        # 如果内存中没有，尝试从Redis加载
        if self.redis_client:
            conv_data = self._load_conversation_from_redis(target_id)
            if conv_data:
                # 同步到内存
                self.conversation_metadata[target_id] = conv_data["metadata"]
                self.conversations[target_id] = conv_data["messages"]
                return conv_data["messages"]
        
        return []
    
    def _get_rag_context(self, question: str, top_k: int = 3) -> str:
        """
        使用 RAG 检索相关上下文
        
        Args:
            question: 用户问题
            top_k: 返回的上下文数量
        
        Returns:
            检索到的上下文文本（拼接后的字符串）
        """
        if not self.enable_rag or not self.rag_system:
            return ""
        
        try:
            # 执行 RAG 检索
            result = self.rag_system.query(question, top_k=top_k, verbose=False)
            
            # 提取上下文
            contexts = result.get("contexts", [])
            if contexts:
                context_texts = [ctx.get("text", "") for ctx in contexts[:top_k]]
                context_text = "\n\n".join([f"[参考{i+1}]: {text}" for i, text in enumerate(context_texts)])
                print(f"[RAG] 检索到 {len(contexts)} 条相关上下文")
                return context_text
            else:
                print("[RAG] 未检索到相关上下文")
                return ""
        except Exception as e:
            print(f"[RAG] 检索失败: {e}")
            return ""
    
    def _build_messages_for_llm(self, conversation_id: str, user_message: str, rag_context: str = "") -> List[Dict[str, str]]:
        """
        构建发送给 LLM 的消息列表
        
        Args:
            conversation_id: 对话ID
            user_message: 用户消息
            rag_context: RAG 检索到的上下文
        
        Returns:
            消息列表
        """
        messages = []
        
        # 如果有 RAG 上下文，添加系统提示
        if rag_context:
            system_prompt = f"""你是一个智能助手，可以基于参考内容回答问题。请遵循以下规则：
1. 如果参考内容中有相关信息，优先使用参考内容回答
2. 如果参考内容中没有相关信息，可以基于你的知识回答
3. 回答要准确、简洁、有用
4. 如果参考内容与问题无关，直接回答即可

【参考内容】：
{rag_context}

请基于以上参考内容（如果有）回答用户问题。"""
            messages.append({"role": "system", "content": system_prompt})
        else:
            # 基础系统提示
            messages.append({
                "role": "system",
                "content": "你是一个智能助手，请准确、简洁、有用地回答用户问题。"
            })
        
        # 添加历史对话（如果有）
        if conversation_id in self.conversations:
            history = self.conversations[conversation_id]
            # 只保留最近的对话历史（避免超出token限制）
            recent_history = history[-10:]  # 保留最近10轮对话
            for msg in recent_history:
                messages.append({
                    "role": msg.get("role"),
                    "content": msg.get("content")
                })
        
        # 添加当前用户消息
        messages.append({"role": "user", "content": user_message})
        
        return messages
    
    def send_message(self, message: str, conversation_id: Optional[str] = None, use_rag: bool = True) -> Dict[str, Any]:
        """
        发送消息并获取回复
        
        Args:
            message: 用户消息
            conversation_id: 对话ID（如果为None，使用当前对话或创建新对话）
            use_rag: 是否使用 RAG 检索
        
        Returns:
            包含回复和相关信息的字典
        """
        # 确定对话ID
        target_id = conversation_id or self.current_conversation_id
        
        # 如果没有对话，创建新对话
        if not target_id or target_id not in self.conversations:
            target_id = self.create_conversation()
        
        # 确保切换到目标对话
        self.current_conversation_id = target_id
        
        # RAG 检索（如果启用）
        rag_context = ""
        if use_rag and self.enable_rag:
            rag_context = self._get_rag_context(message)
        
        # 构建消息列表
        messages = self._build_messages_for_llm(target_id, message, rag_context)
        
        # 调用 LLM
        try:
            print(f"[对话] 发送消息到 {self.llm_model}...")
            resp = Generation.call(
                model=self.llm_model,
                messages=messages,
                result_format='message'
            )
            
            if resp.status_code == 200:
                # 提取回复
                if hasattr(resp, 'output') and resp.output:
                    if hasattr(resp.output, 'choices') and resp.output.choices:
                        assistant_reply = resp.output.choices[0].message.content
                    elif hasattr(resp.output, 'text'):
                        assistant_reply = resp.output.text
                    elif isinstance(resp.output, str):
                        assistant_reply = resp.output
                    else:
                        assistant_reply = str(resp.output)
                else:
                    assistant_reply = "无法解析响应"
                
                # 保存对话历史（内存）
                self.conversations[target_id].append({
                    "role": "user",
                    "content": message,
                    "timestamp": datetime.now().isoformat()
                })
                self.conversations[target_id].append({
                    "role": "assistant",
                    "content": assistant_reply,
                    "timestamp": datetime.now().isoformat(),
                    "used_rag": bool(rag_context)
                })
                
                # 更新元数据
                metadata = self.conversation_metadata[target_id]
                metadata["message_count"] = len(self.conversations[target_id])
                metadata["updated_at"] = datetime.now().isoformat()
                
                # 如果是第一条消息，使用消息内容作为标题（如果标题还是默认的）
                if metadata.get("title") == "新对话" and len(self.conversations[target_id]) == 2:
                    # 使用第一条用户消息的前30个字符作为标题
                    title = message[:30] if len(message) > 30 else message
                    metadata["title"] = title
                
                # 保存到Redis
                if self.redis_client:
                    try:
                        self._save_conversation_to_redis(
                            target_id, 
                            metadata, 
                            self.conversations[target_id]
                        )
                    except Exception as e:
                        print(f"[Redis] 保存对话到Redis失败: {e}")
                
                print(f"[对话] 收到回复，长度: {len(assistant_reply)} 字符")
                
                return {
                    "success": True,
                    "conversation_id": target_id,
                    "user_message": message,
                    "assistant_reply": assistant_reply,
                    "used_rag": bool(rag_context),
                    "message_count": metadata["message_count"]
                }
            else:
                error_msg = f"生成回复失败: {resp.message}"
                print(f"[错误] {error_msg}")
                return {
                    "success": False,
                    "error": error_msg,
                    "conversation_id": target_id
                }
                
        except Exception as e:
            error_msg = f"调用 LLM 失败: {str(e)}"
            print(f"[错误] {error_msg}")
            import traceback
            traceback.print_exc()
            return {
                "success": False,
                "error": error_msg,
                "conversation_id": target_id
            }
    
    def update_conversation_title(self, conversation_id: str, title: str) -> bool:
        """
        更新对话标题
        
        Args:
            conversation_id: 对话ID
            title: 新标题
        
        Returns:
            是否更新成功
        """
        # 如果内存中有，更新内存
        if conversation_id in self.conversation_metadata:
            self.conversation_metadata[conversation_id]["title"] = title
            self.conversation_metadata[conversation_id]["updated_at"] = datetime.now().isoformat()
        else:
            # 如果内存中没有，尝试从Redis加载
            if self.redis_client:
                conv_data = self._load_conversation_from_redis(conversation_id)
                if conv_data:
                    self.conversation_metadata[conversation_id] = conv_data["metadata"]
                    self.conversations[conversation_id] = conv_data["messages"]
                    self.conversation_metadata[conversation_id]["title"] = title
                    self.conversation_metadata[conversation_id]["updated_at"] = datetime.now().isoformat()
                else:
                    print(f"[对话] 对话不存在: {conversation_id}")
                    return False
            else:
                print(f"[对话] 对话不存在: {conversation_id}")
                return False
        
        # 更新Redis
        if self.redis_client:
            try:
                metadata = self.conversation_metadata[conversation_id]
                messages = self.conversations.get(conversation_id, [])
                self._save_conversation_to_redis(conversation_id, metadata, messages)
            except Exception as e:
                print(f"[Redis] 更新对话标题到Redis失败: {e}")
        
        print(f"[对话] 更新对话标题: {conversation_id} -> {title}")
        return True
    
    def export_conversation(self, conversation_id: str, file_path: Optional[str] = None) -> str:
        """
        导出对话历史到文件
        
        Args:
            conversation_id: 对话ID
            file_path: 文件路径（如果为None，自动生成）
        
        Returns:
            导出文件路径
        """
        if conversation_id not in self.conversations:
            raise ValueError(f"对话不存在: {conversation_id}")
        
        if not file_path:
            metadata = self.conversation_metadata.get(conversation_id, {})
            title = metadata.get("title", "对话").replace("/", "_").replace("\\", "_")
            timestamp = datetime.now().strftime("%Y%m%d_%H%M%S")
            file_path = f"conversation_{title}_{timestamp}.json"
        
        export_data = {
            "conversation_id": conversation_id,
            "metadata": self.conversation_metadata.get(conversation_id, {}),
            "messages": self.conversations[conversation_id]
        }
        
        with open(file_path, "w", encoding="utf-8") as f:
            json.dump(export_data, f, ensure_ascii=False, indent=2)
        
        print(f"[导出] 对话已导出到: {file_path}")
        return file_path
    
    def import_conversation(self, file_path: str) -> str:
        """
        从文件导入对话历史
        
        Args:
            file_path: 文件路径
        
        Returns:
            导入的对话ID
        """
        with open(file_path, "r", encoding="utf-8") as f:
            import_data = json.load(f)
        
        conversation_id = import_data.get("conversation_id", str(uuid.uuid4()))
        self.conversations[conversation_id] = import_data.get("messages", [])
        self.conversation_metadata[conversation_id] = import_data.get("metadata", {
            "title": "导入的对话",
            "created_at": datetime.now().isoformat(),
            "updated_at": datetime.now().isoformat(),
            "message_count": len(import_data.get("messages", []))
        })
        
        print(f"[导入] 对话已从文件导入: {file_path}")
        return conversation_id


# 全局对话系统实例
_chat_system = None


def get_chat_system(api_key: str = "sk-2c036d80d14a443f8769e072bb09a2e1", enable_rag: bool = True) -> ChatSystem:
    """
    获取对话系统实例（单例模式）
    
    Args:
        api_key: DashScope API Key
        enable_rag: 是否启用 RAG
    
    Returns:
        ChatSystem 实例
    """
    global _chat_system
    if _chat_system is None:
        _chat_system = ChatSystem(api_key=api_key, enable_rag=enable_rag)
    return _chat_system


if __name__ == "__main__":
    # 测试代码
    print("=" * 60)
    print("多轮对话系统测试")
    print("=" * 60)
    
    # 初始化对话系统
    print("\n[初始化] 正在初始化对话系统...")
    try:
        chat = ChatSystem(enable_rag=True)
        print("[初始化] 对话系统初始化成功\n")
    except Exception as e:
        print(f"[初始化] 失败: {e}")
        import traceback
        traceback.print_exc()
        exit(1)
    
    # 测试1: 创建新对话
    print("=" * 60)
    print("测试1: 创建新对话")
    print("=" * 60)
    conv_id = chat.create_conversation()
    print(f"创建的对话ID: {conv_id}\n")
    
    # 测试2: 发送消息（带 RAG）
    print("=" * 60)
    print("测试2: 发送消息（带 RAG 检索）")
    print("=" * 60)
    result = chat.send_message("如何制作鱼香茄子？", use_rag=True)
    if result["success"]:
        print(f"用户: {result['user_message']}")
        print(f"助手: {result['assistant_reply']}")
        print(f"使用 RAG: {result['used_rag']}")
    else:
        print(f"错误: {result.get('error')}")
    print()
    
    # 测试3: 继续对话
    print("=" * 60)
    print("测试3: 继续对话（多轮对话）")
    print("=" * 60)
    result = chat.send_message("需要准备哪些材料？")
    if result["success"]:
        print(f"用户: {result['user_message']}")
        print(f"助手: {result['assistant_reply']}")
    print()
    
    # 测试4: 获取对话列表
    print("=" * 60)
    print("测试4: 获取对话列表")
    print("=" * 60)
    conv_list = chat.get_conversation_list()
    for conv in conv_list:
        print(f"ID: {conv['conversation_id']}")
        print(f"标题: {conv['title']}")
        print(f"消息数: {conv['message_count']}")
        print(f"最后消息: {conv.get('last_message', '无')}")
        print()
    
    # 测试5: 获取对话历史
    print("=" * 60)
    print("测试5: 获取对话历史")
    print("=" * 60)
    history = chat.get_conversation_history(conv_id)
    for msg in history:
        print(f"[{msg.get('role')}]: {msg.get('content')[:100]}...")
    print()
    
    # 测试6: 创建第二个对话
    print("=" * 60)
    print("测试6: 创建第二个对话")
    print("=" * 60)
    conv_id2 = chat.create_conversation(title="小红书相关问题")
    result = chat.send_message("小红书的特点是什么？", use_rag=True)
    if result["success"]:
        print(f"用户: {result['user_message']}")
        print(f"助手: {result['assistant_reply'][:200]}...")
    print()
    
    # 测试7: 查看所有对话
    print("=" * 60)
    print("测试7: 查看所有对话")
    print("=" * 60)
    conv_list = chat.get_conversation_list()
    print(f"共有 {len(conv_list)} 个对话:")
    for conv in conv_list:
        print(f"  - {conv['title']} ({conv['message_count']} 条消息)")
    
    print("\n" + "=" * 60)
    print("测试完成")
    print("=" * 60)
